package juc.blockqueue.priorityblockingqueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * @ClassName EventProcessor
 * @PackageName juc.blockqueue.priorityblockingqueue
 * @projectName myThread
 * @Description 2. 事件处理系统
 * @Author games
 * @Date 2025/9/4 上午11:34
 * @Version 1.0
 */
class Event implements Comparable<Event> {
    private final long timestamp;
    private final int priority;
    private final String eventData;

    public Event(long timestamp, int priority, String eventData) {
        this.timestamp = timestamp;
        this.priority = priority;
        this.eventData = eventData;
    }

    @Override
    public int compareTo(Event other) {
        // 按优先级排序，优先级相同时按时间戳排序
        int result = Integer.compare(other.priority, this.priority);
        return result != 0 ? result : Long.compare(this.timestamp, other.timestamp);
    }

    // getters...
    public String getEventData() { return eventData; }
    public int getPriority() { return priority; }
}

public class EventProcessor {
    public static void main(String[] args) {
        BlockingQueue<Event> eventQueue = new PriorityBlockingQueue<>();

        // 事件生产者
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    // 模拟不同优先级的事件
                    int priority = (int) (Math.random() * 5) + 1;
                    eventQueue.put(new Event(System.currentTimeMillis(), priority, "Event-" + i));
                    System.out.println("Generated Event-" + i + " with priority " + priority);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();

        // 事件处理器
        new Thread(() -> {
            try {
                while (true) {
                    Event event = eventQueue.take();
                    System.out.println("Processing: " + event.getEventData() +
                            " (Priority: " + event.getPriority() + ")");
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
}

